#pragma once
#include <iostream>
#include <cerrno>
#include <unistd.h>
#include <string>
#include <strings.h>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Log.hpp"
#include "Comm.hpp"
#include "sockaddr.hpp"
#define BUFFERSIZE 1024

class UDP_server
{
public:
    UDP_server(in_port_t server_port)
        : _sockfd(-1)
        , _sk(server_port)
    {}

    ~UDP_server()
    {}

    // 初始化server端
    void Init()
    {
        // 创建socket
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd == -1)
        {
            _log.LogMessage(ClassFile, Error, "server socket error -> errno : %d strerror : %s\n", errno, strerror(errno));
            exit(SocketError);
        }
        _log.LogMessage(ClassFile, Info, "server socket success, _fd = %d\n", _sockfd);

        // 绑定网络信息
        int ret = ::bind(_sockfd, (const struct sockaddr *)(&_sk.addr_in()), _sk.len());
        if (ret == -1)
        {
            _log.LogMessage(ClassFile, Error, "server bind error -> errno : %d strerror : %s\n", errno, strerror(errno));
            exit(BindError);
        }
    }

    // 接收网络信息
    void Start()
    {
        sleep(5);
        char buffer[BUFFERSIZE];
        // 服务端一直运行，不退出，除非我们人为退出
        while (true)
        {
            // 输出型参数，获取到客户端的套接字信息
            
            struct sockaddr_in client;
            socklen_t client_len = sizeof(client);
            ssize_t ret = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)(&client), &client_len);

            Sockaddr tmp(client);
            if (ret > 0)
            {
                buffer[ret] = 0;
                std::cout <<  tmp.PrintDebug() << ": " << buffer << std::endl;
            }
        }
    }

private:
    int _sockfd;
    Sockaddr _sk; // 初始化sockaddr
};
